<template>
    <page-container title="用户管理">
        <template #extra>
            <el-input 
                v-model="search" 
                placeholder="请输入关键字" 
                style="width: 50%;height: 30px;margin-right: 20px;" 
                clearable
            />
            <el-button 
                style="margin-right: 30px; background-color: #5defc1; color: white" 
                @click="loadUserList" 
                plain
            >查询</el-button>
        </template>

        <el-table :data="userList" style="width: 100%" v-loading="loading">
            <el-table-column type="index" fixed label="序号" width="80"/>
            <el-table-column prop="username" label="用户名" width="120"/>
            <el-table-column prop="email" label="邮箱" width="180"/>
            <el-table-column prop="phone" label="手机号" width="120"/>
            <el-table-column prop="gender" label="性别" width="120"/>
            <el-table-column prop="age" label="年龄" width="120"/>
            <el-table-column prop="address" label="地址" width="150"/>
            <el-table-column prop="userPic" label="头像" width="80">
                <template #default="{ row }">
                    <el-image
                        style="width: 40px; height: 40px; border-radius: 50%"
                        :src="row.userPic || ''"
                        :preview-src-list="row.userPic ? [row.userPic] : []"
                        fit="cover"
                    >
                        <template #error>
                            <div class="image-slot">
                                <el-icon><User /></el-icon>
                            </div>
                        </template>
                    </el-image>
                </template>
            </el-table-column>
            <el-table-column prop="createTime" label="注册时间" width="180">
                <template #default="{ row }">
                    {{ formatDateTime(row.createTime) }}
                </template>
            </el-table-column>
            <el-table-column prop="updateTime" label="登录时间" width="180">
                <template #default="{ row }">
                    {{ formatDateTime(row.updateTime) }}
                </template>
            </el-table-column>
            <el-table-column label="操作" min-width="200" >
                <template #default="scope">
                    <el-button-group>
                        <el-button 
                            type="danger" 
                            size="small"
                            @click="handleDelete(scope.row)"
                        >
                            删除
                        </el-button>
                    </el-button-group>
                </template>
            </el-table-column>
          <template #empty>
            <el-empty description="暂无数据" />
          </template>
        </el-table>

        <template #pagination>
            <div class="pagination-container" style="margin-right: 200px">
                <el-pagination
                    v-show="total > 0"
                    v-model:current-page="currentPage"
                    v-model:page-size="pageSize"
                    :page-sizes="[10, 20, 30, 40]"
                    :background="true"
                    layout="total, sizes, prev, pager, next, jumper"
                    :total="total"
                    @size-change="handleSizeChange"
                    @current-change="handleCurrentChange"
                />
            </div>
        </template>
    </page-container>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { User } from '@element-plus/icons-vue'
import PageContainer from '@/components/PageContainer.vue'
import { getUserList, deleteUser } from '@/api/user/user'

const userList = ref([])
const loading = ref(false)
const search = ref('')
const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(0)

// 加载用户列表
const loadUserList = async () => {
    loading.value = true
    try {
        const res = await getUserList({
            pageNum: currentPage.value,
            pageSize: pageSize.value,
            search: search.value
        })
        console.log(res)
        if (res.code === 200) {
            userList.value = res.data.records
            total.value = res.data.total
        } else {
            ElMessage.error(res.message || '获取用户列表失败')
        }
    } catch (error) {
        console.error('获取用户列表失败：', error)
        ElMessage.error('获取用户列表失败')
    } finally {
        loading.value = false
    }
}


// 处理删除
const handleDelete = async (row) => {
    try {
        await ElMessageBox.confirm(
            '删除后无法恢复，确定要删除该用户吗？',
            '提示',
            {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }
        )
        
        const res = await deleteUser(row.userId)
        if (res.code === 200) {
            ElMessage.success('删除成功')
            loadUserList()
        } else {
            ElMessage.error(res.message || '删除失败')
        }
    } catch (error) {
        if (error !== 'cancel') {
            console.error('删除失败：', error)
            ElMessage.error('删除失败')
        }
    }
}

// 分页处理
const handleSizeChange = (val) => {
    pageSize.value = val
    currentPage.value = 1
    loadUserList()
}

const handleCurrentChange = (val) => {
    currentPage.value = val
    loadUserList()
}

// 格式化日期
const formatDateTime = (dateStr) => {
    if (!dateStr) return '--'
    const date = new Date(dateStr)
    return date.toLocaleString('zh-CN', {
        year: 'numeric',
        month: '2-digit',
        day: '2-digit',
        hour: '2-digit',
        minute: '2-digit',
        hour12: false
    })
}

onMounted(() => {
    loadUserList()
})
</script>

<style scoped>
.pagination-container {
    margin-top: 20px;
    display: flex;
    justify-content: flex-end;
}

.el-button-group {
    display: flex;
    gap: 8px;
}

.image-slot {
    display: flex;
    justify-content: center;
    align-items: center;
    width: 100%;
    height: 100%;
    background: #f5f7fa;
    color: #909399;
}

:deep(.el-image) {
    border-radius: 50%;
    overflow: hidden;
}
</style>